<!--
 * @Date: 2023-04-01 23:44:22
 * @Author: Black
 * @LastEditTime: 2023-04-10 15:51:44
 * @FilePath: \store_admin\src\components\ImageMain.vue
 * @Description: 
-->
<template>
  <el-main class="image_main" v-loading="loading">
    <div class="top p-3">
      <el-row :gutter="20">
        <el-col :span="8" :offset="0" v-for="(item, index) in list" :key="index">
          <el-card shadow="hover" :body-style="{ padding: '0px' }" class="relative mb-3"
            :class="{ 'border-violet-500': item.checked }">
            <el-image :src="item.url" fit="cover" :preview-src-list="[item.url]" :initial-index="0"
              class="w-full h-[150px]"></el-image>
            <div class="image_title">{{ item.name }}</div>
            <div class="flex items-center justify-center p-2">
              <el-checkbox class="mr-2" v-model="item.checked" v-if="openChoose" @change="handleChooseChange(item)" />
              <el-button class="btn1" type="primary" size="small" text @click="handleEdit(item)">重命名</el-button>
              <el-button class="btn2" type="primary" size="small" text @click="handleDelete(item.id)">删除</el-button>
            </div>
          </el-card>

        </el-col>
      </el-row>

    </div>
    <div class="bottom">
      <el-pagination background layout="prev,pager,next" :total="total" :page-size="limit" :current-page="currentPage"
        @current-change="getImageData" />
    </div>
  </el-main>

  <el-drawer title="图片上传" v-model="drawer">
    <UploadFile :data="{ image_class_id }" @success="handleUploadSuccess" />
  </el-drawer>
</template>

<script setup>
import { getImageList, updateImage, deleteImage } from '../api/image';
import { ref, computed } from 'vue';
import { showPrompt, toast, showAlert } from '../composables/util';
import UploadFile from './UploadFile.vue';

// 分页
const currentPage = ref(1)
const total = ref(0)
const limit = ref(9)

const list = ref([])
const loading = ref(false)
const image_class_id = ref(0)

// 获取数据
function getImageData(p = null) {
  if (typeof p == "number") {
    currentPage.value = p
  }
  loading.value = true
  getImageList(image_class_id.value, currentPage.value)
    .then(res => {
      total.value = res.totalCount
      list.value = res.list.map(o => {
        o.checked = false
        return o
      })
    })
    .finally(() => {
      loading.value = false
    })
}

// 根据分类id重新加载图片列表
const loadData = (id) => {
  currentPage.value = 1
  image_class_id.value = id
  getImageData()
}

// 图片重命名
const handleEdit = (item) => {
  // console.log('handleEdit  item:', item)
  showPrompt("重命名", item.name)
    .then(({ value }) => {
      // console.log('handleEdit  res:', res)
      loading.value = true
      updateImage(item.id, value)
        .then(res => {
          toast("修改成功")
          getImageData()
        })
        .finally(() => {
          loading.value = false
        })
    })
}

// 删除图片
const handleDelete = (id) => {
  console.log('handleDelete  id:', id)
  loading.value = true
  showAlert("是否确认删除该图片", "删除")
    .then(res => {
      deleteImage([id]).then(res => {
        toast("删除成功")
        getImageData()
      })
    })
    .finally(() => {
      loading.value = false
    })
}

// 上传图片
const drawer = ref(false)
const openUploadFile = () => drawer.value = true

// 上传成功
const handleUploadSuccess = () => {
  getImageData(1)
}

// 动态传递参数 子组件接收父组件传递过来的参数
const props = defineProps({
  openChoose: {
    type: Boolean,
    default: false
  },
  limit: {
    type: Number,
    default: 1
  }
})

// 选中图片
const emit = defineEmits(["choose"])
const checkedImage = computed(() => list.value.filter(o => o.checked))
const handleChooseChange = (item) => {
  if (item.checked && checkedImage.value.length > props.limit) {
    item.checked = false
    return toast(`最多只能选中${props.limit}张图片`, 'error')
  }
  // 
  emit("choose", checkedImage.value)
}

// 向父组件暴露方法，以对象的形式传递给父组件
// 父组件可以通过模版 ref 的方式获取当前实例（对象）
defineExpose({
  loadData,
  openUploadFile
})

</script>

<style scoped>
.image_main {
  position: relative;
}

.image_main .top {
  position: absolute;
  width: 100%;
  top: 0;
  right: 0;
  bottom: 50px;
  overflow-y: auto;
}

.image_main .top::-webkit-scrollbar {
  width: 0px;
}

.image_main .bottom {
  position: absolute;
  bottom: 0;
  height: 50px;
  left: 0;
  right: 0;
  @apply flex items-center justify-center;
}

.image_title {
  position: absolute;
  top: 130px;
  left: -1px;
  right: -1px;
  text-align: center;
  @apply text-sm truncate text-gray-100 bg-opacity-40 bg-gray-600;
}

.btn1 {
  @apply text-violet-500;
}

.btn2 {
  @apply text-gray-500 font-medium;
}
</style>